
package io.renren.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.entity.SysUserRoleEntity;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.models.auth.In;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 系统用户
 *
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleService sysRoleService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String)params.get("key");
		Long createUserId = (Long)params.get("createUserId");
		QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
		wrapper.like(StringUtils.isNotBlank(username), "real_name", username).or().like(StringUtils.isNotBlank(username), "num",username);
//				.eq(createUserId != null, "create_user_id", createUserId);

		if (params.get("type")!=null){
			Integer type = Integer.parseInt((String) params.get("type"));
			List<SysUserRoleEntity> list = sysUserRoleService.list(new QueryWrapper<SysUserRoleEntity>().eq("role_id", type));
			List<Long> list1 = list.stream().map((entity) -> {
				return entity.getUserId();
			}).collect(Collectors.toList());
			wrapper.in("user_id", list1);
		}
//		if(params.get("key")!=null && !params.get("key").equals("")){
//			wrapper.like("num", params.get("key"));
//		}
		if(params.get("dormId")!=null && !params.get("dormId").equals("")){
			wrapper.like("dorm_id", Integer.parseInt((String)params.get("dormId")));
		}
		IPage<SysUserEntity> page = this.page(
			new Query<SysUserEntity>().getPage(params),
			wrapper
		);

		return new PageUtils(page);
	}
	@Override
	public PageUtils queryPage01(Map<String, Object> params) {
		QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();

		if(params.get("dormId")!=null){
			wrapper.eq("dorm_id", params.get("dormId"));
		}
		IPage<SysUserEntity> page = this.page(
				new Query<SysUserEntity>().getPage(params),
				wrapper
		);
		return new PageUtils(page);
	}


	@Override
	public List<String> queryAllPerms(Long userId) {
		return baseMapper.queryAllPerms(userId);
	}

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		return baseMapper.queryByUserName(username);
	}

	@Override
	@Transactional
	public void saveUser(SysUserEntity user) {
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		this.save(user);
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional
	public void update(SysUserEntity user) {
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
		}
		this.updateById(user);
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	public void deleteBatch(Long[] userId) {
		this.removeByIds(Arrays.asList(userId));
	}

	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setPassword(newPassword);
		return this.update(userEntity,
				new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
	}


	/**
	 * 检查角色是否越权
	 */
	private void checkRole(SysUserEntity user){
//		if(user.getRoleIdList() == null || user.getRoleIdList().size() == 0){
//			return;
//		}
//		//如果不是超级管理员，则需要判断用户的角色是否自己创建
//		if(user.getCreateUserId() == Constant.SUPER_ADMIN){
//			return ;
//		}
//
//		//查询用户创建的角色列表
//		List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());
//
//		//判断是否越权
//		if(!roleIdList.containsAll(user.getRoleIdList())){
//			throw new RRException("新增用户所选角色，不是本人创建");
//		}
		if(user.getRoleIdList() == null){
			return;
		}
		//如果不是超级管理员，则需要判断用户的角色是否自己创建
		if(user.getCreateUserId() == Constant.SUPER_ADMIN){
			return ;
		}

		//查询用户创建的角色列表
		List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

		//判断是否越权
		if(!roleIdList.containsAll(user.getRoleIdList())){
			throw new RRException("新增用户所选角色，不是本人创建");
		}
	}
}